import { RouteLocationNormalizedLoaded } from 'vue-router';
import { CacheEnum } from '@/enum/cacheEnum';
import { defineStore } from 'pinia';
import { IMenu } from '#/menu';
import router from '@/router';
import utils from '@/utils';
export default defineStore('menu', {
  state: () => {
    return {
      menus: [] as IMenu[],
      historyMenus: [] as IMenu[]
    };
  },
  actions: {
    init() {
      this.getMenuByRoute();
      this.historyMenus = utils.storage.get(CacheEnum.HISTORY_MENUS) ?? ([] as IMenu[]);
    },
    // 根据路由获取菜单
    getMenuByRoute() {
      const parentMenus = this.getParentMenus();
      const tempMenus = parentMenus.map(route => {
        let menu: IMenu = { ...route.meta.menu };
        menu.children = route.children
          .filter(route => route.meta?.menu)
          .map(route => {
            return { ...route.meta?.menu, route: route.name };
          }) as IMenu[];
        return menu;
      });
      this.menus = tempMenus.filter(menu => menu.children?.length);
    },
    // 获取所有的一级路由
    getParentMenus() {
      return router.getRoutes().filter(route => route.children.length && route.meta.menu);
    }
  }
});
